#include "LibReceiver.h"
#include "TestProgressControl.pb.h"
#include "TestResultSaving.pb.h"
#include "TestInitialResult.pb.h"
#include "VoiceControl.pb.h"
#include "test_framework\TFUnitTest.h"
#include "test_framework\TFTest.h"
#include "test\BDTestFactory.h"
#include "voice\VoicePlayer.h"
#include "voice\VoiceUtils.h"

LibReceiver* LibReceiver::m_pInstance = NULL;

LibReceiver::LibReceiver()
{
	RegisterCallback(LIB_RECEIVER, UI_LIB_MSG_TEST_PROGRESS_CONTROL, std::bind(&LibReceiver::OnTestProgressControl, this, std::placeholders::_1));
	RegisterCallback(LIB_RECEIVER, UI_LIB_MSG_TEST_RESULT_SAVING, std::bind(&LibReceiver::OnTestResultSaving, this, std::placeholders::_1));
	RegisterCallback(LIB_RECEIVER, UI_LIB_MSG_VOICE_CONTROL, std::bind(&LibReceiver::OnVoiceControl, this, std::placeholders::_1));

}


LibReceiver::~LibReceiver()
{

}

LibReceiver* LibReceiver::GetInstance()
{
	if (m_pInstance == NULL) {
		m_pInstance = new LibReceiver;
	}
	return m_pInstance;
}

void LibReceiver::Destroy()
{
	if (m_pInstance == NULL) {
		return;
	}
	delete m_pInstance;
	m_pInstance = NULL;
}

void LibReceiver::OnTestProgressControl(void* ptr)
{
	TestProgressControl* control = static_cast<TestProgressControl*>(ptr);
	TestInitialResult* result = new TestInitialResult;

	switch (control->test_cmd())
	{
	case TestProgressControl_Command_TEST_INIT:
	{
		TFUnitTest::GetInstance()->RegisterTest(BDTestFactory::GetInstance());
		for (int i = 0; i < TFUnitTest::GetInstance()->TestCount(); ++i)
		{
			TestInitialResult_TestItem* item = result->add_item();
			item->set_test_name(TFUnitTest::GetInstance()->GetTest(i)->GetTestName());
			item->set_test_id(i);
			item->set_initial_result(true);
		}
		SendMsg(LIB_SENDER, LIB_UI_MSG_TEST_INITIAL_RESULT, result);
		break;
	}
	case TestProgressControl_Command_TEST_START:
	{
		int index = control->test_id(0);
		TFUnitTest::GetInstance()->GetTest(index)->SetShouldRun(true);
		TFUnitTest::GetInstance()->StartAllTests();
		break;
	}
	case TestProgressControl_Command_TEST_STOP:
	{
		TFUnitTest::GetInstance()->SkipCurrentTest();
		TFUnitTest::GetInstance()->Wait();
		TFUnitTest::Destroy();
		break;
	}
	default:
		break;
	}
}

void LibReceiver::OnTestResultSaving(void* ptr)
{
	TestResultSaving* saving = static_cast<TestResultSaving*>(ptr);
	
}

void LibReceiver::OnVoiceControl(void* ptr)
{
	VoiceControl* voiceControl = static_cast<VoiceControl*>(ptr);
	switch (voiceControl->cmd())
	{
	case VoiceControl_Command_VOICE_INIT:
		VoicePlayer::GetInstance();
		break;
	case VoiceControl_Command_VOICE_DEINIT:
		VoicePlayer::Destroy();
		break;
	case VoiceControl_Command_VOICE_PLAY:
	{
		BDString str = VoiceUtils::GetVoicePath(voiceControl->play_param().file_path());
		VoicePlayer::GetInstance()->Play(str.c_str());
		break;
	}
	default:
		break;
	}
}